package com.ballmaze.configs;


import com.ballmaze.BeanUtil;
import com.ballmaze.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;


/**
 * 服务器
 *
 * @author OnlyMate
 * @ClassName: WebSocket
 * @Description: TODO
 */
@Component
@ServerEndpoint(value = "/{route}/{userid}")
@Slf4j
public class WebSocket {

    private static WebSocketService webSocketService;

    private WebSocketService getWebSocketService() {
        if (webSocketService == null) {
            webSocketService = BeanUtil.getBean(WebSocketService.class);
        }
        return webSocketService;
    }

    private Session session;

    private String userid;

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userid") String userid, @PathParam("route") String route) throws IOException {
        this.session = session;
        this.userid = userid;
        log.info("userid:" + userid + "  route:" + route);
//        log.info("userid:" + userid);
        if (!getWebSocketService().add(session, route, userid)) {
            //如果添加失败，则关闭session
            session.close();
            log.info("onOpen Session Closed");
        } else {
            log.info("【新建连接】" + userid + "，连接总数:{}", getWebSocketService().size());
        }
    }

    /**
     * 断开连接
     */
    @OnClose
    public void onClose(@PathParam("userid") String userid, @PathParam("route") String route) {
        getWebSocketService().remove(session, route, userid);
        log.info("【断开连接】，连接总数:{}", getWebSocketService().size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("webSocket发生错误！session：{}", session);
        error.printStackTrace();
    }


    /**
     * 接收到信息
     *
     * @param message
     */
    @OnMessage
    public void onMessage(Session session, String message) {
//        log.info("【收到】{}，客户端的信息:{}，连接总数:{}", userid, message, getWebSocketService().size());
        webSocketService.onMessage(userid, session, message);
    }

    public Session getSession() {
        return this.session;
    }
}